import axios from "axios";
const baseURL = import.meta.env.VITE_API_BASE_URL;

const customToken = localStorage.getItem("token");

const API_BASE_URL = baseURL;
const http = axios.create({
  baseURL: API_BASE_URL, // Optional: specify your API base URL if needed
  headers: {
    Authorization: `Bearer ${customToken}`,
  },
});



/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  // 默认参数
  const _defaults = { '_t': new Date().getTime() }
  // 防止缓存，GET请求默认带_t参数
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      ..._defaults,
    }
  }

  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  if (response.data.code === 401 || response.data.code === 10001) {
    return Promise.reject(response.data.msg)
  }
  return response.data
}, error => {
  console.error(error)
  return Promise.reject(error)
})

export default http;
